import http from "http";
import express from "express";
import webpush from "web-push";
import bodyParser from "body-parser";
const app = express();
const server = http.createServer(app);
let subscriptions = [];
app.use(express.static("public"));
app.use(bodyParser.json());
const vapidKeys = {
  publicKey:
    "BDHXr8OZctYQzBiW-FQ4osJZXYLjfFGBHyl01R_XiEYj1RUF1JU8RHj21uK0y869W_uZ1yaoZ4LIMFNQSIQaZPA",
  privateKey: "0giGJkzsdv__05yklxNDb_cMQ-Yd2mhNhHumIbE7luw",
};
const VAPID_PUBLIC_KEY = vapidKeys.publicKey;
const VAPID_PRIVATE_KEY = vapidKeys.privateKey;
webpush.setVapidDetails(
  "mailto:example@domain.com",
  VAPID_PUBLIC_KEY,
  VAPID_PRIVATE_KEY
);
/**
 * 全局接口监听
 */
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Credentials", true);
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, token, authorization"
  );
  res.header("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.get("/getKey", (req, res) => {
  res.cookie("token", "123456");
  res.json({ code: 0, data: Math.random() * 1000 });
});

app.post("/subscribe", (req, res) => {
  console.log(req.body);
  const subscription = req.body;
  subscriptions.push(subscription);
  console.log(subscriptions);
  res.status(201).json({ message: "订阅成功" });
});

app.get("/push", async (req, res) => {
  const payload = JSON.stringify({
    title: "新消息",
    body: "这是来自 Node.js 的推送",
    icon: "/logo.png",
  });

  const sendAll = subscriptions.map((sub) =>
    webpush.sendNotification(sub, payload).catch(console.error)
  );
  console.log(sendAll);
  await Promise.all(sendAll);

  res.json({ message: "推送已发送" });
});

server.listen(80, () => {
  console.log("server is up and running on port 8000");
});
